<template>
  <view class="content">
    <!-- 搜索+轮播图 -->
	<view class="search-banner">
		<!-- 自定义导航栏 -->
		<view
		  class="custom-nav-bar"
		  :style="{ height: customNavBarHeight + 'px', paddingTop: statusBarHeight + 'px' }"
		>
		  <view class="search-bar">
		    <input type="search" placeholder="请输入搜索内容" v-model="searchKeyword" @confirm="handleSearch" />
		    <view class="search-icon" @click="handleSearch">
		      <uni-icons type="search" size="20" color="#999999"></uni-icons>
		    </view>
		  </view>
		</view>
		
		<!-- 轮播图 -->
		<view class="swiper-box">
		  <swiper
		    class="swiper"
		    :indicator-dots="indicatorDots"
		    :autoplay="autoplay"
		    :interval="interval"
		    :duration="duration"
		    indicator-color="#e0e0e0"
		    indicator-active-color="#ff8d1a"
		    circular
		  >
		    <swiper-item
		      class="swiper-item"
		      v-for="(item, index) in swiperList"
		      :key="index"
		    >
		      <image :src="item.img" :alt="item.title" mode="aspectFill"></image>
		    </swiper-item>
		  </swiper>
		</view>
	</view>

    <!-- 分类列表 -->
    <view class="category-list">
      <view
        class="category-item"
        v-for="(item, index) in categoryList"
        :key="index"
        @click="goToCategory"
      >
        <image :src="item.img" mode="aspectFit"></image>
        <text>{{ item.title }}</text>
      </view>
    </view>

    <!-- 热门专区 -->
     <view class="hot-zone">
      <image style="margin: 2px 10rpx;"
        :src="public_img + '/img/img16990918abc404050.png'"
        mode="scaleToFill"
      /> 
      <view class="hot-zone-item" style="margin: 0px 10rpx;">
        <image style="margin-bottom: 20rpx;" :src="public_img + '/img/img16991418abc41b368.png'" mode="aspectFill"></image>
        <image
          :src="public_img + '/img/img16991518abc41da78.png'"
          mode="scaleToFill"
        />
      </view>
    </view>

    <!-- 热销商品 -->
    <view class="hot-products">
      <view class="section-title">
        <image
          :src="public_img + '/img/hott.png'" mode="scaleToFill" style="width:30px;height: 30px;"
        />
        热销商品</view>
      <view class="waterfall-container">
        <view class="waterfall-column" v-for="(column, colIndex) in waterfallColumns" :key="colIndex">
          <view
            class="product-item-waterfall"
            v-for="(item, index) in column"
            :key="index"
            @click="goToProductDetail(item)"
          >
            <image :src="item.img" mode="widthFix"></image>
            <view class="product-info-waterfall">
              <view class="product-title">{{ item.title }}</view>
              <view class="product-synopsis">{{ item.synopsis }}</view>
              <view class="product-price">
                <text class="price">¥{{ item.price }}</text>
                <text class="original-price">¥{{ item.original_price }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 无数据提示 -->
    <view v-if="!productList.length && !loading" class="no-data">
      <text>暂无商品数据</text>
    </view>
  </view>
</template>

<script>
// 引入全局配置
import { public_img } from "@/static/public.js";
// 引入首页相关接口
import { homeApi } from "@/api/indexAPI.js";
// 引入uni-icons组件
import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue';

console.log("引入的homeApi:", homeApi); // 添加调试信息

export default {
  components: {
    uniIcons
  },
  data() {
    return {
      public_img: public_img, // 将全局变量注入到data中以便在模板中使用
      title: "首页",
      statusBarHeight: 0, // 状态栏高度
      customNavBarHeight: 44, // 自定义导航栏高度（包括状态栏）
      indicatorDots: true,
      autoplay: true,
      interval: 5000,
      duration: 500,
      loading: true,
      searchKeyword: '', // 搜索关键词
      // 轮播图数据
      swiperList: [
        { img: public_img + '/img/home.jpg' },
        { img: public_img + '/img/home.jpg' },
        { img: public_img + '/img/home.jpg' }
      ],
      // 分类列表数据
      categoryList: [
        { img: public_img + '/img/my.png', title: '分类1' },
        { img: public_img + '/img/my.png', title: '分类2' },
        { img: public_img + '/img/my.png', title: '分类3' },
        { img: public_img + '/img/my.png', title: '分类4' }
      ],
      // 商品列表数据
      productList: [],
      // 瀑布流列数
      waterfallColumnCount: 2,
      // 瀑布流列数据
      waterfallColumns: [[], []]
    };
  },
   onLoad() {
    console.log("首页onLoad执行");
    // 获取设备状态栏高度
    this.getStatusBarHeight();
    // 页面加载时检查用户登录状态
    const isLoggedIn = this.checkLoginStatus();
    // 只有在用户已登录的情况下才获取首页数据
    if (isLoggedIn) {
      // 获取首页数据
      console.log("准备调用getHomeData方法");
      this.getHomeData();
    }
  },
  methods: {
    // 获取设备状态栏高度
    getStatusBarHeight() {
      try {
        const systemInfo = uni.getSystemInfoSync();
        this.statusBarHeight = systemInfo.statusBarHeight || 0;
        // 设置自定义导航栏总高度（状态栏高度 + 导航栏主体高度）
        this.customNavBarHeight = this.statusBarHeight + 74;
      } catch (err) {
        console.error("获取状态栏高度失败", err);
      }
    },
    
    changeIndicatorDots(e) {
      this.indicatorDots = !this.indicatorDots;
    },
    
    changeAutoplay(e) {
      this.autoplay = !this.autoplay;
    },
    
    intervalChange(e) {
      this.interval = e.target.value;
    },
    
    durationChange(e) {
      this.duration = e.target.value;
    },
    
    checkLoginStatus() {
      try {
        // 从本地存储中获取用户信息
        const userinfo = uni.getStorageSync("userinfo");
        console.log("获取到的用户信息:", userinfo);

        // 如果没有用户信息，则跳转到登录页面
        if (!userinfo) {
          console.log("未登录，准备跳转到登录页面");
          this.logoutAndRedirect("请先登录");
          return false; // 返回false表示未登录
        } else {
          console.log("用户已登录");
          return true; // 返回true表示已登录
        }
      } catch (err) {
        console.error("检查登录状态失败", err);
        this.logoutAndRedirect("登录状态异常，请重新登录");
        return false; // 返回false表示未登录
      }
    },
    
    // 退出登录并跳转到登录页面
    logoutAndRedirect(message = "登录已过期，请重新登录") {
      try {
        // 清除所有相关的本地存储数据
        uni.removeStorageSync("userinfo");
        uni.removeStorageSync("token");
        // 可以根据需要清除其他缓存数据
        
        uni.showToast({
          title: message,
          icon: "none",
          duration: 1500
        });
        
        // 延迟跳转以显示提示信息
        setTimeout(() => {
          // 使用redirectTo跳转到登录页面
          uni.redirectTo({
            url: "/pages/login/login",
            fail: (err) => {
              console.error("跳转到登录页面失败:", err);
              // 如果redirectTo失败，尝试switchTab（如果login是tab页面）
              uni.switchTab({
                url: "/pages/login/login",
                fail: (err2) => {
                  console.error("switchTab到登录页面也失败了:", err2);
                }
              });
            }
          });
        }, 1500);
      } catch (err) {
        console.error("退出登录过程出错:", err);
      }
    },
    
    // 获取首页数据
    getHomeData() {
      this.loading = true;
      console.log("开始调用首页数据接口");
      
      // 使用封装好的API接口
      homeApi
        .getHomeData()
        .then((res) => {
          this.loading = false;
          console.log("首页接口请求成功，返回数据:", res);

          // 检查是否是下线通知 (code=3 且 msg="下线通知")
          if (res && res.code === 3 && res.msg === "下线通知") {
            console.log("收到下线通知，准备跳转到登录页面");
            this.logoutAndRedirect("您的账号已在其他设备登录，请重新登录");
            return;
          }

          if (res.code === 1 && res.data) {
            console.log("数据解析成功");
            // 设置轮播图数据
            if (res.data.swiper && res.data.swiper.length > 0) {
              this.swiperList = res.data.swiper.map(item => ({
                ...item,
                img: item.img.startsWith('http') ? item.img : public_img + item.img
              }));
            }
            console.log("轮播图数据:", this.swiperList);

            // 设置分类列表数据
            if (res.data.type && res.data.type.length > 0) {
              this.categoryList = res.data.type.map(item => ({
                ...item,
                img: item.img.startsWith('http') ? item.img : public_img + item.img
              }));
            }
            console.log("分类列表数据:", this.categoryList);

            // 设置商品列表数据
             if (res.data.list && res.data.list.length > 0) {
              this.productList = res.data.list.map(item => ({
                ...item,
                img: item.img.startsWith('http') ? item.img : public_img + item.img
              }));
              // 构建瀑布流数据
              this.buildWaterfallData();
            }
            console.log("商品列表数据:", this.productList);
          } else if (res.code === 401 || res.code === 403) {
            // 处理登录过期或未授权的情况
            console.log("登录已过期或未授权，准备跳转到登录页面");
            this.logoutAndRedirect("登录已过期，请重新登录");
          } else {
            console.error("首页数据获取失败:", res.msg || "未知错误");
            uni.showToast({
              title: res.msg || "数据获取失败",
              icon: "none",
            });
          }
        })
        .catch((err) => {
          this.loading = false;
          console.error("首页接口请求失败:", err);
          
          uni.showToast({
            title: "网络请求失败，请检查网络连接",
            icon: "none",
          });
          
          // 即使请求失败，也要显示默认数据或空状态
          this.showDefaultData();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 显示默认数据
        showDefaultData() {
      console.log("显示默认数据");
      // 如果没有获取到数据，保持默认数据
      // 这样至少页面不会完全空白
    },

    // 构建瀑布流数据
    buildWaterfallData() {
      // 初始化列数组
      const columns = Array.from({ length: this.waterfallColumnCount }, () => []);
      
      // 将商品列表按顺序分配到各列
      this.productList.forEach((item, index) => {
        const columnIndex = index % this.waterfallColumnCount;
        columns[columnIndex].push(item);
      });
      
      // 更新瀑布流列数据
      this.waterfallColumns = columns;
    },
    
    // 处理搜索
    handleSearch() {
      if (this.searchKeyword.trim()) {
        uni.showToast({
          title: '搜索: ' + this.searchKeyword,
          icon: 'none'
        });
        // 这里可以添加实际的搜索逻辑
        // 例如跳转到搜索结果页面
        // uni.navigateTo({
        //   url: `/pages/search/search?keyword=${this.searchKeyword}`
        // });
      }
    },

    // 跳转到商品详情
    goToProductDetail(item) {
      uni.navigateTo({
        url: `/pages/product/product?id=${item.id}`
      });
    },
    
    // 设置 tabBar 图标
    setTabBarIcons() {
      const homeIcon = uni.getStorageSync('tabbar_icon_home');
      const homeActiveIcon = uni.getStorageSync('tabbar_icon_homeActive');
      const categoryIcon = uni.getStorageSync('tabbar_icon_category');
      const categoryActiveIcon = uni.getStorageSync('tabbar_icon_categoryActive');
      const cartIcon = uni.getStorageSync('tabbar_icon_cart');
      const cartActiveIcon = uni.getStorageSync('tabbar_icon_cartActive');
      const userIcon = uni.getStorageSync('tabbar_icon_user');
      const userActiveIcon = uni.getStorageSync('tabbar_icon_userActive');
      
      if (homeIcon && homeActiveIcon) {
        uni.setTabBarItem({
          index: 0,
          iconPath: homeIcon,
          selectedIconPath: homeActiveIcon
        });
      }
      
      if (categoryIcon && categoryActiveIcon) {
        uni.setTabBarItem({
          index: 1,
          iconPath: categoryIcon,
          selectedIconPath: categoryActiveIcon
        });
      }
      
      if (cartIcon && cartActiveIcon) {
        uni.setTabBarItem({
          index: 2,
          iconPath: cartIcon,
          selectedIconPath: cartActiveIcon
        });
      }
      
      if (userIcon && userActiveIcon) {
        uni.setTabBarItem({
          index: 3,
          iconPath: userIcon,
          selectedIconPath: userActiveIcon
        });
      }
    }
  },
  
  onShow() {
    // 设置 tabBar 图标
    this.setTabBarIcons();
  }
};
</script>


<style>
.content {
  width: 100%;
  background-color: #FAFAFA;
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
  padding-bottom: 100rpx; /* 为tabbar留出空间 */
}

/* 搜索+轮播图 */
.search-banner{
  width: 100%;
  height: 270px;
  background-image: url('https://jht.jingang.icu/img/indexbg.png');
  background-size: cover;
}


/* 自定义导航栏 */
.custom-nav-bar {
  width: 100%;
  /* background-color: #fff; */
  box-sizing: border-box;
  padding: 0 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.search-bar {
  width: 100%;
  padding: 15rpx 0;
  box-sizing: border-box;
  margin-top: 36px; /* 向下移动搜索框，避免被胶囊按钮覆盖 */
  position: relative;
  height: 60rpx;
}


.search-bar input {
  width: 100%;
  height: 60rpx;
  background-color: white;
  border-radius: 30rpx;
  padding: 0 60rpx 0 30rpx; /* 右侧留出空间给搜索图标 */
  font-size: 28rpx;
  box-sizing: border-box;
}

/* 搜索图标 */
.search-icon {
  position: absolute;
  right: 20rpx;
  top: 70%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
  height: 100%;
}

/* 为胶囊按钮留出空间 */
.custom-nav-bar {
  width: 100%;
  box-sizing: border-box;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  padding: 0 15rpx;
  position: relative;
}

.search-bar {
  width: 100%;
  /* padding: 15rpx 110rpx 15rpx 15rpx; 为右侧胶囊按钮留出空间 */
  box-sizing: border-box;
}

.search-bar input {
  width: 100%;
  height: 60rpx;
  background-color: white;
  border-radius: 30rpx;
  padding: 0 60rpx 0 30rpx; /* 右侧留出空间给搜索图标 */
  font-size: 28rpx;
  box-sizing: border-box;
}

/* 轮播图 */
.swiper-box {
  width: 100%;
  padding: 20rpx;
  box-sizing: border-box;
}

.swiper {
  height: 300rpx;
  border-radius: 16rpx;
  overflow: hidden;
}

.swiper-item {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300rpx;
}

.swiper-item image {
  width: 100%;
  height: 100%;
}

/* 分类列表 */
.category-list {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  padding: 20rpx;
  box-sizing: border-box;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 25%;
  padding: 20rpx 0;
  box-sizing: border-box;
}

.category-item image {
  width: 80rpx;
  height: 80rpx;
  margin-bottom: 10rpx;
}

.category-item text {
  font-size: 24rpx;
  color: #333;
}

/* 热门专区 */
.hot-zone{
  width: 100%;
  display: flex;
  height: 180px;
  background-color: white;
  padding: 10rpx 10rpx;
}

.hot-zone > image{
  width: 44%;
  height: 180px;
}

.hot-zone-item{ 
  flex: 1;
  display: flex;
  flex-direction: column;
}

.hot-zone-item image{ 
  width: 100%;
  flex: 1;
}

/* 热销商品 */
.hot-products {
  width: 100%;
  box-sizing: border-box;
}

.section-title {
  font-size: 18px;
  color: #FF8D1A;
  margin: 20rpx 0;
  background-color: white;
  padding: 2%;
  display: flex;
  align-items: center;
}

.product-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.product-item {
  display: flex;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.product-item image {
  width: 200rpx;
  height: 200rpx;
}

.product-info {
  flex: 1;
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.waterfall-container {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 0 20rpx 20rpx;
}

.waterfall-column {
  display: flex;
  flex: 1;
  flex-direction: column;
  margin-right: 15rpx;
}

.waterfall-column:last-child {
  margin-right: 0;
}

.product-item-waterfall {
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
  margin-bottom: 20rpx;
}

.product-item-waterfall image {
  width: 100%;
}

.product-info-waterfall {
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-title {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.product-synopsis {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 20rpx;
  flex: 1;
}

.product-price {
  display: flex;
  align-items: center;
}

.price {
  font-size: 32rpx;
  color: #ff4757;
  font-weight: bold;
  margin-right: 10rpx;
}

.original-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
}

/* 无数据提示 */
.no-data {
  text-align: center;
  padding: 50rpx 0;
  color: #999;
}
</style>